//Given an array nums of n integers and an integer target, find three integers i
//n nums such that the sum is closest to target. Return the sum of the three integ
//ers. You may assume that each input would have exactly one solution. 
//
// 
// Example 1: 
//
// 
//Input: nums = [-1,2,1,-4], target = 1
//Output: 2
//Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
// 
//
// 
// Constraints: 
//
// 
// 3 <= nums.length <= 10^3 
// -10^3 <= nums[i] <= 10^3 
// -10^4 <= target <= 10^4 
// 
// Related Topics 数组 双指针 
// 👍 775 👎 0


package leetcode.editor.cn;

import org.junit.Assert;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//Java：3Sum Closest
class P16ThreeSumClosest {
    public static void main(String[] args) {
        Solution solution = new P16ThreeSumClosest().new Solution();
        // TO TEST
        Assert.assertEquals(solution.threeSumClosest(new int[]{1, 1, -1, -1, 3}, 1),
                1);
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int threeSumClosest(int[] nums, int target) {
            List<List<Integer>> ans = new ArrayList<>();
            if (nums == null || nums.length <= 2) {
                return 0;
            }
            Arrays.sort(nums); // O(nlogn)
            int min = Math.abs(target - (nums[0] + nums[1] + nums[2]));
            int sum = nums[0] + nums[1] + nums[2];
            for (int i = 0; i < nums.length - 2; i++) { // O(n^2)
                if (i > 0 && nums[i] == nums[i - 1]) {
                    continue; // 去掉重复情况
                }
                int left = i + 1, right = nums.length - 1;
                while (left < right) {
                    int remain = target - (nums[i] + nums[left] + nums[right]);
                   if (Math.abs(remain) <= min) {
                        min = Math.abs(remain);
                        sum = nums[i] + nums[left] + nums[right];
                       if (remain == 0) {
                           return sum;
                       }
                        // 现在要增加 left，减小 right，但是不能重复，比如: [-2, -1, -1, -1, 3, 3, 3], i = 0, left = 1, right = 6, [-2, -1, 3] 的答案加入后，需要排除重复的 -1 和 3
                        if (remain > 0) {
                            left++;
                        } else {
                            right--;
                        }
                    } else {
                        if (remain > 0) {
                            left++;
                        } else {
                            right--;
                        }
                    }
                }

            }
            return sum;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}